/*******************************************************************************
 * Package: com.song.keyvalue
 * Type:    MapValue
 * Date:    2024-11-22 16:11
 *
 * Copyright (c) 2024 LTD All Rights Reserved.
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.song.keyvalue;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaSparkContext;
import scala.Tuple2;

import java.util.ArrayList;
import java.util.List;

/**
 * 功能描述： 在一个(K,V)的RDD上调用，K必须实现Ordered接口，返回一个按照key进行排序的(K,V)的RDD
 *
 * @author Songxianyang
 * @date 2024-11-22 16:11
 */
public class SortByKey {
    public static void main(String[] args) {
        // 1.创建配置对象
        SparkConf conf = new SparkConf().setMaster("local[2]").setAppName("sparkCore");

        // 2. 创建sparkContext
        JavaSparkContext sc = new JavaSparkContext(conf);
        List<Tuple2<Integer,String>> list = new ArrayList<>();

        list.add(new Tuple2<>(3,"v1"));
        list.add(new Tuple2<>(2,"v2"));
        list.add(new Tuple2<>(7,"v3"));
        list.add(new Tuple2<>(1,"v4"));

        JavaPairRDD<Integer, String> pairRDD = sc.parallelizePairs(list);
        pairRDD.sortByKey().collect().forEach(System.out::println);
        sc.close();
    }
}
